package demo06_生产者消费者_JUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class B {

    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();



        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

// 等待 --> 业务 --> 通知
class Data {
    private int number = 0 ;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void increment() throws InterruptedException {

        try {
            lock.lock();
            // 业务代码
            while (number != 0) {
                // 等待
                System.out.println(Thread.currentThread().getName() + " => " + "increment未满足条件! 继续等待...");
                condition.await();
            }
            this.number++;
            System.out.println(Thread.currentThread().getName() + " => " + number);
            // 通知其他线程
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void decrement() throws InterruptedException {
        try {
            lock.lock();
            // 业务代码
            while (number == 0) {
                // 等待
                System.out.println(Thread.currentThread().getName() + " => " + "decrement未满足条件! 继续等待...");
                condition.await();
            }
            this.number--;
            System.out.println(Thread.currentThread().getName() + " => " + number);
            // 通知其他线程
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
